package com.liu.efk.zdcq.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * Created by shi860715@126.com
 * Date 2021/5/8 12:34
 * Description
 */
@Slf4j
@Component
public class NettyService {


    /**
     * boss 线程组用于处理连接工作
     */
    private EventLoopGroup boss = new NioEventLoopGroup();
    /**
     * work 线程组用于数据处理
     */
    private EventLoopGroup work = new NioEventLoopGroup();

    @Autowired
    private ServerHandler serverHanlder;




    @Value("${netty.port}")
    private Integer port;

    @PostConstruct
    public void start(){

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss,work)
                .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {

//                    ch.pipeline().addLast(new LineBasedFrameDecoder(102400));
                ByteBuf delimiter = Unpooled.copiedBuffer(">###".getBytes());
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024*1024,delimiter));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new StringEncoder());
                ch.pipeline().addLast(serverHanlder);

            }
        });
        bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的设置，链接缓冲池的大小
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的设置,维持链接的活跃，清除死链接
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的设置,关闭延迟发送

        // bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR ,new FixedRecvByteBufAllocator(20480000));
        //绑定端口
        ChannelFuture future = bootstrap.bind(port);
        if(future.isSuccess()){
            System.out.println("netty server is  started !!!");
        }
    }

    @PreDestroy
    public void destory() throws InterruptedException {
        boss.shutdownGracefully().sync();
        work.shutdownGracefully().sync();
        log.info("关闭Netty");
    }
}
